package com.huatai.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.api.R;
import com.huatai.common.util.EncryptUtils;
import com.huatai.common.util.OkHttpUtil;
import com.huatai.user.dto.ServerInfoDto;
import com.huatai.user.entity.ServerInfo;

import com.huatai.user.mapper.ServerInfoMapper;
import com.huatai.user.service.ServerInfoService;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Service
public class ServerInfoServiceImpl extends ServiceImpl<ServerInfoMapper, ServerInfo> implements ServerInfoService {

	@Value("${childServer.port}")
	private String port;

	@Override
	public R saveinfo(ServerInfo serverInfo) {
		Long count = this.count(new LambdaQueryWrapper<ServerInfo>().eq(ServerInfo::getServerIp, serverInfo.getServerIp()));
		if (count > 0) {
			return R.fail("服务器信息已存在");
		}

		R resultData = this.getServerStatus(serverInfo.getServerIp());
		if(!resultData.isSuccess()){
			return R.fail("服务器连接异常");
		}

		LocalDateTime now = LocalDateTime.now();
		serverInfo.setUpdateTime(now);
		serverInfo.setMaxLink(serverInfo.getMaxLink());
//		serverInfo.setServerPassword(EncryptUtils.encryptByRsa(serverInfo.getServerPassword()));
		this.save(serverInfo);

		CompletableFuture.runAsync(() -> {
			//调用渲染服务器进行数据同步
			childDataUpdate(serverInfo);
		});

		return R.data(serverInfo.getId());
	}

	@Override
	public R getServerStatus(String serverIp) {
		String url = "http://" + serverIp + ":" + port + "/serverStatus";
		try {
			Response response = OkHttpUtil.sendOkHttpClientWithResponse(url, "GET", null, null);
			if (response != null && response.isSuccessful()) {
				return R.success("子公司监控服务正常");
			} else {
				return R.fail("子公司监控服务异常，状态码：" + (response != null ? response.code() : "无响应"));
			}
		} catch (Exception e) {
			return R.fail("子公司监控服务异常：" + e.getMessage());
		}
	}

	public void childDataUpdate(ServerInfo info){
		String url = "http://"+info.getServerIp()+":"+port+"/updateMaxLinkNum?maxNum="+info.getMaxLink()+"&serverIp="+info.getServerIp();
		Object resultObj = OkHttpUtil.sendOkHttpClient(url, "GET", null, null);
		System.out.println(info.getServerIp()+"渲染服务器数据同步结果："+resultObj);
	}

	@Override
	public R deleteServerInfo(Long serverId) {
		Integer info = this.baseMapper.getServerInfoByServerID(serverId);
		if (info > 0) {
			return R.fail("当前服务信息已绑定项目，请先解绑");
		}
		this.removeById(serverId);
		return R.success("服务器信息删除成功");
	}

	@Override
	public boolean updateServerInfo(ServerInfo serverInfo) {
		ServerInfo info = this.baseMapper.selectById(serverInfo.getId());
		if(info == null){
			return false;
		}
		if(StringUtils.isNotBlank(serverInfo.getServerName())){
			info.setServerName(serverInfo.getServerName());
		}
		if(StringUtils.isNotBlank(serverInfo.getServerIp())){
			info.setServerIp(serverInfo.getServerIp());
		}
		if(serverInfo.getServerPort() != null){
			info.setServerPort(serverInfo.getServerPort());
		}
		if(StringUtils.isNotBlank(serverInfo.getServerUser())){
			info.setServerUser(serverInfo.getServerUser());
		}
		if(serverInfo.getMaxLink() != null){
			info.setMaxLink(serverInfo.getMaxLink());
		}
		LocalDateTime now = LocalDateTime.now();
		serverInfo.setUpdateTime(now);

		R resultData = this.getServerStatus(serverInfo.getServerIp());
		if(!resultData.isSuccess()){
			return false;
		}

		CompletableFuture.runAsync(() -> {
			//调用渲染服务器进行数据同步
			childDataUpdate(serverInfo);
		});
		return this.updateById(serverInfo);
	}

	@Override
	public R getChangePage(Page page,ServerInfoDto pageDto) {
		LambdaQueryWrapper<ServerInfo> wrapper = new LambdaQueryWrapper<>();
		wrapper.like(StringUtils.isNotBlank(pageDto.getServerIp()),ServerInfo::getServerIp,pageDto.getServerIp());
		wrapper.like(StringUtils.isNotBlank(pageDto.getServerName()),ServerInfo::getServerName,pageDto.getServerName());
		wrapper.like(StringUtils.isNotBlank(pageDto.getServerUser()),ServerInfo::getServerUser,pageDto.getServerUser());
		wrapper.orderByDesc(ServerInfo::getUpdateTime);
		Page<ServerInfo> pageResult = this.baseMapper.selectPage(page, wrapper);
		return R.data(pageResult);
	}

	@Override
	public List<ServerInfo> getALLInfo() {
		List<ServerInfo> result = this.baseMapper.getALLInfo();
		return result;
	}

	@Override
	public Integer getMaxLinkValue(String serverIp) {
		return this.baseMapper.getMaxLinkValue(serverIp);
	}

	@Override
	public R<ServerInfo> detail(Long id) {
		return R.data(this.baseMapper.selectById(id));
	}
}
